using System;
using System.Linq;

namespace KTOP.Core.Netlists
{
    public class Module
    {
        public int Id { get; private set; }
        public int PinCount { get; set; }

        private Pin[] _pins;
        public Pin this[int pin]
        {
            get
            {
                if (pin >= PinCount || pin < 0) 
                    throw new ArgumentOutOfRangeException("pin");

                return _pins[pin];
            }

        }


        public static Module Create(int moduleId, int pinCount)
        {
            var module = new Module
                       {
                           PinCount = pinCount,
                           Id = moduleId
                       };

            module._pins = Enumerable.Range(0, pinCount).Select(p => new Pin(p, module)).ToArray();

            return module;
        }


        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof (Module)) return false;
           
            return Equals((Module) obj);
        }

        public bool Equals(Module other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return other.Id == Id && other.PinCount == PinCount;
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return (Id*397) ^ PinCount;
            }
        }
    }
}